<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 代理模式的简单实现
        // 声明对象
        var Girl = function (name) {
            this.name = name;
        }

        var Boy = function (girl) {
            this.girl = girl;
            this.sendGift = function (gift) {
                console.log("hi," + this.girl.name + "，送你礼物：" + gift);
            }
        }
        // 代理对象

        var ProxyObj = function (girl) {
            this.girl = girl;
            this.sendGift = function (gift) {
                (new Boy(this.girl)).sendGift(gift);
            }
        }

        var girl = new Girl("小芳");
        var proxyObj = new ProxyObj(girl);
        proxyObj.sendGift("999朵玫瑰")

        // 使用代理模式可以实现图片懒加载
        var myImage = (function () {
            var imgNode = document.createElement('img');
            document.body.appendChild(imgNode);
            var img = new Image(); // 代理对象，先展示等待的小图片，接着负责拉取真是图片
            img.onload = function () { // 当真实图片加载完成后触发
                imgNode.src = this.src;
            }
            return {
                setSrc: function (src) {
                    // 先展示等待的小图片
                    imgNode.src = "https://img.lanrentuku.com/img/allimg/1212/5-121204193R0.gif";
                    // 为了明显的看到效果，这里设置成异步，延迟3秒
                    var timer = setTimeout(() => {
                        img.src = src; // 把真实图片地址给代理对象，等到代理对象的图片加载完成之后，将图片给imgNode，让其展示真正的图片
                        clearTimeout(timer)
                    }, 3000)

                }
            }
        })()


        // 封装一下代码
        var myImage2 = (function () {
            var imgNode = document.createElement('img');
            document.body.appendChild(imgNode);
            return {
                setSrc: function (src) {
                    imgNode.src = src;
                }
            }
        })()

        var proxyImage = (function () {
            var img = new Image();
            img.onload = function () {
                myImage2.setSrc(this.src);
            }
            return {
                setSrc: function (src) {
                    myImage2.setSrc("https://img.lanrentuku.com/img/allimg/1212/5-121204193R0.gif");
                    var timer = setTimeout(() => {
                        img.src = src; // 把真实图片地址给代理对象，等到代理对象的图片加载完成之后，将图片给imgNode，让其展示真正的图片
                        clearTimeout(timer)
                    }, 3000)
                }
            }
        })()

        // proxyImage.setSrc(
        //     'https://tse1-mm.cn.bing.net/th/id/OIP.1z2fsEK2KdtGn5rKR-wnHQHaJ3?pid=ImgDet&rs=1'
        // )
        myImage.setSrc(
            'https://tse1-mm.cn.bing.net/th/id/OIP.1z2fsEK2KdtGn5rKR-wnHQHaJ3?pid=ImgDet&rs=1'
        )
    </script>
</body>

</html>